package com.bodacn.keypoint;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketService extends Service {
    private Socket clientSocket = null;
    private ServerSocket mServerSocket = null;
    private SocketAcceptThread socketAcceptThread = null;
    private SocketReceiveThread socketReceiveThread = null;
    private SocketReceiver socketReceiver;

    public static final String SOCKER_ACTION = "com.bodacn.keypoint.Control";
    public static final String SOCKER_RCV = "com.bodacn.keypoint.ReceiveStr";
    private int socketPort=45678;//服务端口
    private boolean stop = true;

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("service", "socket onBind");
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("service", "socket service created");
        socketReceiver = new SocketReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SOCKER_ACTION);
        registerReceiver(socketReceiver, filter);
        socketAcceptThread = new SocketAcceptThread();
        // 开启 Socket 监听线程
        socketAcceptThread.start();
    }


    @Override
    public void onStart(Intent intent, int startId) {
        Log.d("service", "socket service start");


    }


    @Override
    public void onDestroy() {
        Log.d("service", "socket service destroy!");


    }


    public class SocketReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("SocketReceiver：onReceive");
            String action = intent.getAction();
            if(action.equals(SOCKER_ACTION)) {
                String sub_action = intent.getExtras().getString("ACTION");
                if(sub_action.equals("reconnect")) {
                    Log.d("service", "socket service: reconnect.");
                    socketAcceptThread = new SocketAcceptThread();
                    // 开启 Socket 监听线程
                    socketAcceptThread.start();
                }
                if(sub_action.equals("sendmsg")) {
                    String MsgInfo=intent.getExtras().getString("CONTENT");
                    Log.d("service", "Send Message: "+MsgInfo);
                    if ((clientSocket!=null)&&(clientSocket.isConnected())) {
                        //连接存在,执行发送消息类;
                        new sendCommandThread(MsgInfo).run();
                    } else{
                        Intent sendIntent = new Intent(SOCKER_RCV);
                        sendIntent.putExtra("action", "ReturnMsg");
                        sendIntent.putExtra("content", "客户端尚未连接！");
                        // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                        sendBroadcast(sendIntent);
                        Log.d("service", "socket service - msg:客户端尚未连接！::Over");
                    }
                }
            }
        }
    }


    /*发送命令线程*/
    class sendCommandThread extends Thread {
        private String command;
        public sendCommandThread(String aCommand){
            this.command = aCommand;
        }
        public void run(){
            try{
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
                out.print(command);
                out.flush();
            }catch (UnknownHostException e){
            }catch (IOException e){
            }
        }
    }


    private class SocketAcceptThread extends Thread
    {
        @Override
        public void run()
        {
            Log.d("service", "socket service - SocketAcceptThread::run");
            try {
                // 实例化ServerSocket对象并设置端口号为 12589
                if (mServerSocket!=null) mServerSocket.close();
                mServerSocket = new ServerSocket(socketPort);
                Log.d("service", "socket service - run---1");
                // 等待客户端的连接（阻塞）
                if (clientSocket!=null) clientSocket.close();
                Log.d("service", "socket service - run---2");
                clientSocket = mServerSocket.accept();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (clientSocket!=null) {
                socketReceiveThread = new SocketReceiveThread(clientSocket);
                stop = false;
                // 开启接收线程
                socketReceiveThread.start();
                Intent sendIntent = new Intent(SOCKER_RCV);
                sendIntent.putExtra("action", "ClientIP");
                sendIntent.putExtra("content", clientSocket.getInetAddress().getHostAddress());
                // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                sendBroadcast(sendIntent);
                Log.d("service", "socket service - SocketAcceptThread::Over--------->Success");
            } else Log.e("service", "socket service - SocketAcceptThread::Over--------->Error");
        }
    }


    private class SocketReceiveThread extends Thread
    {
        private InputStream mInputStream = null;
        private byte[] buf=new byte[2048];
        private String str = null;
        Socket sUsed;
        SocketReceiveThread(Socket s)
        {
            Log.d("service", "socket service - SocketReceiveThread");
            System.out.println(s);
            try {
                mInputStream=s.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        @Override
        public void run()
        {
            Log.d("service", "socket service - SocketReceiveThread::run");
            while((!stop) && (!mServerSocket.isClosed()))
            {
                System.out.println(clientSocket);
                this.buf = new byte[2048];
                // 读取输入的数据(阻塞读)
                Log.d("service", "socket service - SocketReceiveThread::run--1");
                try {
                    int length = mInputStream.read(buf);
                    if(length==-1) {
                        try {
                            sUsed.sendUrgentData(0xff);
                        }
                        catch(Exception ex) {
                            mInputStream.close();
                            clientSocket.close();
                            // 链接已断开
                            Log.v("service", "disconnect!!!");
                            stop = true;
                            Intent sendIntent = new Intent(SOCKER_RCV);
                            sendIntent.putExtra("action", "Disconnect");
                            sendIntent.putExtra("content", "read is -1 & Urgent Exception!");
                            sendBroadcast(sendIntent);

                        }
                    }
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    Log.d("service", "socket service - SocketReceiveThread::run--error");
                }
                Log.d("service", "socket service - SocketReceiveThread::run--2");
                if (!stop) {
                    // 字符编码转换
                    try {
                        this.str = new String(this.buf, "GB2312").trim();
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Intent sendIntent = new Intent(SOCKER_RCV);
                    sendIntent.putExtra("action", "RcvStr");
                    sendIntent.putExtra("content", this.str);
                    // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                    sendBroadcast(sendIntent);
                }
            }
        }
    }
}